package mencrypt

import (
	"encoding/hex"
	"golang.org/x/crypto/argon2"
	"golang.org/x/crypto/bcrypt"
)

type PasswordEncoder interface {
	Encoder(password, salt string) (string, error)
	CompareHashAndPassword(hashPassword, password, salt string) (bool, error)
}
type Argon2PasswordEncoder struct {
}

func (ew Argon2PasswordEncoder) Encoder(password, salt string) (string, error) {
	hash := argon2.IDKey([]byte(password), []byte(salt), 1, 64*1024, 4, 32)
	return hex.EncodeToString(hash), nil
}
func (ew Argon2PasswordEncoder) CompareHashAndPassword(hashPassword, password, salt string) (bool, error) {
	pass, _ := ew.Encoder(password, salt)
	return pass == hashPassword, nil
}

type BcryptPasswordEncoder struct {
}

func (ew BcryptPasswordEncoder) Encoder(password, salt string) (string, error) {
	if hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost); err == nil {
		return hex.EncodeToString(hash), nil
	} else {
		return "", err
	}
}
func (ew BcryptPasswordEncoder) CompareHashAndPassword(hashPassword, password, salt string) (bool, error) {
	if hash, err := hex.DecodeString(hashPassword); err == nil {
		if bcrypt.CompareHashAndPassword(hash, []byte(password)) == nil {
			return true, nil
		} else {
			return false, nil
		}
	} else {
		return false, err
	}

}
